package com.ts.api.http.receive.biz;

import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.reflection.CopyUtils;
import com.gitee.apanlh.util.valid.Assert;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.constant.api.ApiEnum;
import com.ts.api.common.constant.api.ApiServiceCodeEnum;
import com.ts.api.common.context.ApiContext;
import com.ts.api.common.util.ApiDictUtils;
import com.ts.api.exp.ApiMsgException;
import com.ts.api.http.receive.entity.apply.req.ApiReceiveApplyYouQianLai;
import com.ts.api.http.receive.entity.dataexchange.req.ApiReceiveDataExchangeYouQianLai;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveApply;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveDecrypt;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveNotice;
import com.ts.api.module.api.convert.receive.entity.ApiReceivePhoneMd5DataExchange;
import com.ts.api.module.api.convert.receive.handler.ApiReceivePhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiUserRequest;

import java.util.Map;

/**
 * 有钱来全流程
 * 【有钱钱包对接文档】链接: https://apifox.com/apidoc/shared-64fcec58-85e4-409f-aafd-e2b8776dbe3f 访问密码: youqian
 * @author 李源聪
 */
public abstract class ApiReceivePhoneMd5YouQianLai implements ApiReceivePhoneMd5ConvertHandler {

    @Override
    public Map<String, String> requireParam(RequestVO requestVO) throws Exception {
        //  获取请求体参数
        Map<String, Object> map = JsonUtils.toMap(requestVO.getBody());
        String method = String.valueOf(map.get("method"));
        String timestamp = String.valueOf(map.get("timestamp"));
        String params = String.valueOf(map.get("params"));
        String sign = String.valueOf(map.get("sign"));
        String serialNo = String.valueOf(map.get("serialNo"));

        Assert.isNotEmptyThrows(method, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("method")));
        Assert.isNotEmptyThrows(timestamp, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("timestamp")));
        Assert.isNotEmptyThrows(params, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("params")));
        Assert.isNotEmptyThrows(sign, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("sign")));
        Assert.isNotEmptyThrows(serialNo, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("serialNo")));

        if (Eq.str("user.api.check", method)) {
            ApiContext.SERVICE_CODE.set(ApiServiceCodeEnum.A0001.getCode());
        }
        if (Eq.str("user.api.apply", method)) {
            ApiContext.SERVICE_CODE.set(ApiServiceCodeEnum.A0002.getCode());
        }

        //  返回需要的数据Map
        return MapUtils.newHashMap(newMap -> {
            newMap.put("method", method);
            newMap.put("timestamp", timestamp);
            newMap.put("params", params);
            newMap.put("sign", sign);
            newMap.put("serialNo", serialNo);
        });
    }

    @Override
    public ApiUserRequest parseDataExchange(ApiReceiveDecrypt apiReceiveDecrypt) throws Exception {
        ApiReceiveDataExchangeYouQianLai parse = apiReceiveDecrypt.parse(ApiReceiveDataExchangeYouQianLai.class);
        ApiUserRequest apiUserRequest = CopyUtils.copy(parse, ApiUserRequest.class);
        fieldMapping(apiUserRequest);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> respDataExchange(ApiReceivePhoneMd5DataExchange dataExchangeMessage) throws Exception {
        boolean suc = dataExchangeMessage.hasBizSuc();

        // 失败
        if (!suc) {
            Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
            resultMap.put("code", "200");
            resultMap.put("msg", dataExchangeMessage.getBizMsg());
            resultMap.put("data", MapUtils.newLinkedHashMap(dataMap -> dataMap.put("bumpStatus", "2")));
            return resultMap;
        }

        //成功
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        resultMap.put("code", "200");
        resultMap.put("msg", "成功");
        resultMap.put("data", MapUtils.newLinkedHashMap(dataMap -> {
            //  撞库状态
            dataMap.put("bumpStatus", "1");
            //  产品名称
            dataMap.put("partnerProductName", dataExchangeMessage.getDisplayName());
            //  公司主体名
            dataMap.put("partnerCompanyName", dataExchangeMessage.getOrgName());
            //  下游产品logo
            dataMap.put("partnerLogo",dataExchangeMessage.getLogoPath());
            //  价格Decimal(10,2)
            dataMap.put("productPrice", dataExchangeMessage.getPrice());
            //  页面显示扩展字段
            dataMap.put("partnerProtocolList", CollUtils.newArrayList(newList -> {
                Map<String, Object> protocol = MapUtils.newLinkedHashMap();
                protocol.put("name", "个人信息授权协议");
                protocol.put("url", "https://axh.rongyiudai.com/h5ViewProtocol?uniqueCode=1fc1379861b34ef0898d7864c33b18e2");
                newList.add(protocol);
            }));
        }));
        return resultMap;
    }

    @Override
    public ApiUserRequest parseApply(ApiReceiveDecrypt apiReceiveDecrypt) throws Exception {
        ApiReceiveApplyYouQianLai parse = apiReceiveDecrypt.parse(ApiReceiveApplyYouQianLai.class);
        ApiUserRequest apiUserRequest = CopyUtils.copy(parse, ApiUserRequest.class);
        fieldMapping(apiUserRequest);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> respApply(ApiReceiveApply applyMessage) throws Exception {
        boolean suc = applyMessage.hasBizSuc();

        // 失败
        if (!suc) {
            Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
            resultMap.put("code", "200");
            resultMap.put("msg", applyMessage.getBizMsg());
            resultMap.put("data", MapUtils.newLinkedHashMap(dataMap -> dataMap.put("applyStatus", "2")));
            return resultMap;
        }

        // 成功
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        resultMap.put("code", "200");
        resultMap.put("msg", "成功");
        resultMap.put("data", MapUtils.newLinkedHashMap(dataMap -> {
            dataMap.put("applyStatus", "1");
            //  价格Decimal(10,2) CPS结算价格
            dataMap.put("settlementPrice", applyMessage.getPrice());
        }));
        return resultMap;
    }

    @Override
    public void fieldMapping(ApiUserRequest apiUserRequest) {
        //  年龄(21岁-55岁)
        String age1 = apiUserRequest.getAge();
        if (ValidParam.isNotEmpty(age1)) {
            String age = ApiDictUtils.convertAge(apiUserRequest.getAge());
            apiUserRequest.setAge(age);
        }

        //  gender 性别：1-男、2-女
        //  sex 性别
        //  0 男
        //  1 女
        //  2 未知
        String sex = apiUserRequest.getSex();
        {
            String sexChoose = ChooseEq.create()
                    .when(sex, "1", "0")
                    .when(sex, "2", "1")
                    .end("2");
            apiUserRequest.setSex(sexChoose);
        }

        //  城市
        String city1 = apiUserRequest.getAreaCode();
        if (ValidParam.isNotEmpty(city1)) {
            String splitCity = city1.split(",")[1];
            String city = ApiDictUtils.getAreaNameByCode(splitCity);
            apiUserRequest.setCity(city);
        }

        // job 10->上班族，20->自由职业者，30->企业主
        // career
        //   1	上班族
        //   2	自由职业
        //   3	企业主（有营业执照）
        //   4	公务员或事业单位
        //   5	个体户
        String career = apiUserRequest.getCareer();
        if (ValidParam.isNotEmpty(career)) {
            String value = ChooseEq.create()
                    .when(career, "10", "1")
                    .when(career, "20", "2")
                    .when(career, "30", "3")
                    .end();
            apiUserRequest.setCareer(value);
        }

        // houseProperty 房产：0-无房产、1-有房产、2-有且接受抵押
        // realEstateInfo 房产情况
        // 1 无房产
        // 2 有房不抵押
        // 3 有房可抵押
        // 4 有房产
        // 5 有按揭房产
        // 6 有全款房产
        String realEstateInfo = apiUserRequest.getRealEstateInfo();
        if (ValidParam.isNotEmpty(realEstateInfo)) {
            String value = ChooseEq.create()
                    .when(realEstateInfo, "0", "1")
                    .when(realEstateInfo, "1", "4")
                    .when(realEstateInfo, "2", "3")
                    .end();
            apiUserRequest.setRealEstateInfo(value);
        }

        // carProperty 车产：0-无车产、1-有、2-有且接受抵押
        // carInfo 车辆情况
        // 1 无车产
        // 2 有车不抵押
        // 3 有车可抵押
        // 4 有车产
        String carInfo = apiUserRequest.getCarInfo();
        if (ValidParam.isNotEmpty(carInfo)) {
            String value = ChooseEq.create()
                    .when(carInfo, "0", "1")
                    .when(carInfo, "1", "4")
                    .when(carInfo, "2", "3")
                    .end();
            apiUserRequest.setCarInfo(value);
        }

        // socialSecurity 社保：0-无社保、1-六个月以下、2、六个月以上
        // socialSecurity 社保缴纳
        // 1 无社保
        // 2 缴纳6个月以下
        // 3 缴纳6个月以上
        // 4 有社保
        String socialSecurity = apiUserRequest.getSocialSecurity();
        if (ValidParam.isNotEmpty(socialSecurity)) {
            String value = ChooseEq.create()
                    .when(socialSecurity, "0", "1")
                    .when(socialSecurity, "1", "2")
                    .when(socialSecurity, "2", "3")
                    .end();
            apiUserRequest.setSocialSecurity(value);
        }

        //  housingFund 公积金：0-无、1-六个月以下、2、六个月以上
        // providentFund 公积金
        // 1 无公积金
        // 2 缴纳6个月以下
        // 3 缴纳6个月以上
        // 4 有公积金
        String providentFund = apiUserRequest.getProvidentFund();
        if (ValidParam.isNotEmpty(providentFund)) {
            String value = ChooseEq.create()
                    .when(providentFund, "0", "1")
                    .when(providentFund, "1", "2")
                    .when(providentFund, "2", "3")
                    .end();
            apiUserRequest.setProvidentFund(value);
        }

        //  insurance 保单：0-无保单、1-缴纳不足1年、2-缴纳1年以上
        // insurancePolicy 保险保单
        // 1 无保险保单
        // 2 缴纳未满1年
        // 3 缴纳1年以上
        // 4 有保险保单
        String insurancePolicy = apiUserRequest.getInsurancePolicy();
        if (ValidParam.isNotEmpty(insurancePolicy)) {
            String value = ChooseEq.create()
                    .when(insurancePolicy, "0", "1")
                    .when(insurancePolicy, "1", "2")
                    .when(insurancePolicy, "2", "3")
                    .end();
            apiUserRequest.setInsurancePolicy(value);
        }

        // creditInvestigation 0-无逾期、1-有逾期
        // overdue 逾期
        // 1 无逾期
        // 2 当前有逾期
        // 3 一年以内无逾期
        String overdue = apiUserRequest.getOverdue();
        if (ValidParam.isNotEmpty(overdue)) {
            String value = ChooseEq.create()
                    .when(overdue, "0", "1")
                    .when(overdue, "1", "2")
                    .end();
            apiUserRequest.setOverdue(value);
        }

        // sesameCredit  芝麻分：0-无芝麻分、2-650 ~ 700分、3-700分以上、4-600分以下、5-600~650分
        // sesameCredit 芝麻分
        // 1 600分以下
        // 2 600~649分
        // 3 650~699分
        // 4 700分以上
        String sesameCredit = apiUserRequest.getSesameCredit();
        if (ValidParam.isNotEmpty(sesameCredit)) {
            String value = ChooseEq.create()
                    .when(sesameCredit, "2", "3")
                    .when(sesameCredit, "3", "4")
                    .when(sesameCredit, "4", "1")
                    .when(sesameCredit, "5", "2")
                    .end();
            apiUserRequest.setSesameCredit(value);
        }

        // applyLimit  贷款金额需 1-0万 ~3万、2-3万 ~5万、3-5万 ~10万、4-10万 ~20万
        // loanAmount 贷款金额
        // 1 3万以下
        // 2 5万-10万
        // 3 10万-20万
        // 4 20万以上
        String loanAmount = apiUserRequest.getLoanAmount();
        if (ValidParam.isNotEmpty(loanAmount)) {
            String value = ChooseEq.create()
                    .when(loanAmount, "1", "1")
                    .when(loanAmount, "2", "1")
                    .when(loanAmount, "3", "2")
                    .when(loanAmount, "4", "3")
                    .end();
            apiUserRequest.setLoanAmount(value);
        }

        // payoffForm  1-银行转账、2-银行代发、3-现金
        // salaryPayMethod
        // 1 银行代发打卡
        // 2 现金收入
        // 3 个人转账
        String salaryPayMethod = apiUserRequest.getSalaryPayMethod();
        if (ValidParam.isNotEmpty(salaryPayMethod)) {
            String value = ChooseEq.create()
                    .when(salaryPayMethod, "1", "1")
                    .when(salaryPayMethod, "2", "1")
                    .when(salaryPayMethod, "3", "2")
                    .end();
            apiUserRequest.setSalaryPayMethod(value);
        }
    }

    @Override
    public Object reqPullApplyNotice(ApiReceiveNotice apiReceiveNotice) {
        return null;
    }

    @Override
    public boolean respPullApplyNotice(String responseBody) {
        return false;
    }

    @Override
    public Object reqPushApplyNotice(ApiReceiveNotice apiReceiveNotice) {
        return null;
    }

    @Override
    public boolean respPushApplyNotice(String responseBody) {
        return false;
    }
}
